/*
 * @Author: szx
 * @Date: 2021-12-09 13:15:15
 * @LastEditTime: 2021-12-09 13:26:11
 * @Description:
 * @FilePath: \leetcode\700-799\794\794.js
 */
/**
 * @param {string[]} board
 * @return {boolean}
 */
var validTicTacToe = function (board) {
    let xCount = 0,
        oCount = 0;
    for (const row of board) {
        for (const c of row) {
            if (c == 'X') xCount++;
            else if (c == 'O') oCount++;
        }
    }
    // 数量判定，不同或者少一个就返回false
    if (oCount != xCount && oCount !== xCount - 1) {
        return false;
    }
    // 如果X赢了但是数量对不上，也返回失败
    if (win(board, 'X') && oCount !== xCount - 1) {
        return false;
    }
    if (win(board, 'O') && oCount !== xCount) {
        return false;
    }
    return true;
};

const win = (board, p) => {
    for (let i = 0; i < 3; ++i) {
        if (p === board[0][i] && p === board[1][i] && p === board[2][i]) {
            return true;
        }
        if (p === board[i][0] && p === board[i][1] && p === board[i][2]) {
            return true;
        }
    }
    if (p === board[0][0] && p === board[1][1] && p === board[2][2]) {
        return true;
    }
    if (p === board[0][2] && p === board[1][1] && p === board[2][0]) {
        return true;
    }
    return false;
};
